package com.woniu.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.Result;
import com.woniu.commons.util.JwtUtil;
import com.woniu.commons.util.RedisUtil;
import com.woniu.model.dto.GoodsOrderDto;
import com.woniu.model.form.OrderByShoppingCarForm;
import com.woniu.model.form.PageForm;
import com.woniu.model.model.YGoodsOrder;
import com.woniu.model.param.OrderByShoppingCarParam;
import com.woniu.model.param.OrderPayParam;
import com.woniu.model.param.PageParam;
import com.woniu.service.YGoodsOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 胡歌
 * @since 2024年05月28日
 */
@RestController
@RequestMapping("/yGoodsOrder")
@Api(tags = "商城订单的接口")
public class YGoodsOrderController {

    @Resource
    private YGoodsOrderService goodsOrderService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 用户查询我的订单
     * @param form :pageNum; pageSize;
     * @param token
     * @return page
     * @throws YogaException
     */
    @PostMapping("/selectOrders")
    @ApiOperation(value = "用户查询，我的订单")
    private Result selectOrders(@RequestBody PageForm form, @RequestHeader String token) throws YogaException {
        String refreshToken = redisUtil.get(token);//从短token取出键
        int userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("userId").toString());

        Page<YGoodsOrder> page = goodsOrderService.selsectOrders(BeanUtil.toBean(form, PageParam.class), userId);

        return Result.newInstance(Page.class).setData(page).setCode(200).setMsg("查询成功");
    }




    /**
     *发起支付
     * @param orderNum：订单编号
     * @param token
     * @return
     * @throws Exception
     */
    @GetMapping("/pay")
    @ApiOperation(value = "发起支付")
    public Result pay(String orderNum, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);//从短token取出键
        int userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("userId").toString());

        OrderPayParam orderPayParam = new OrderPayParam();
        orderPayParam.setOrderNum(orderNum);
        orderPayParam.setUserId(userId);

        return Result.newInstance(null).setCode(200).setMsg("发起支付成功").setData(goodsOrderService.pay(orderPayParam));
    }


    /**
     * 给支付宝回调的接口
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    @ApiOperation(value = "给支付宝回调的接口")
    public String payNotify(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        goodsOrderService.payNotify(params);
        return "SUCCESS";
    }

    /**
     * 商城订单下单接口
     * @param form: //收货地址  addressName;
     *     //收货人 name;
     *     //收货人电话  phoneNum;
     *     //商品集合 goodsIdList;
     *     下单人的用户id userId;
     * @param token
     * @return 订单的dto
     * @throws YogaException
     */
    @PostMapping("orderByShoppingCar")
    @ApiOperation("商城订单下单接口")
    public Result order(@RequestBody OrderByShoppingCarForm form, @RequestHeader String token) throws Exception {

        String refreshToken = redisUtil.get(token);//从短token取出键
        int userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("userId").toString());

        OrderByShoppingCarParam param = BeanUtil.toBean(form, OrderByShoppingCarParam.class);
        param.setUserId(userId);

        GoodsOrderDto dto = goodsOrderService.orderByShoppingCar(param);
        return Result.newInstance(null).setCode(200).setMsg("下单成功").setData(dto);
    }


    /**
     * 通过一个订单编号查询一个订单回去
     * @param orderNum：订单编号
     * @return 一个订单
     */
    @GetMapping("/byId/{id}")
    @ApiOperation(value = "通过一个订单编号查询一个订单回去")
    public Result<YGoodsOrder>byId(@PathVariable("id") String orderNum){
        YGoodsOrder goodsOrder = goodsOrderService.getById(orderNum);

        return Result.newInstance(YGoodsOrder.class).setData(goodsOrder).setCode(200).setMsg("查询成功");
    }

    /**
     * getOneId通过一个订单编号查询一个订单回去
     * @param orderNum：订单编号
     * @return 一个订单
     */
    @GetMapping("/getOneId/{id}")
    @ApiOperation(value = "getOneId通过一个订单编号查询一个订单回去")
    public Result<YGoodsOrder>getOneId(@PathVariable("id") String orderNum){
        YGoodsOrder goodsOrder = goodsOrderService.getOneId(orderNum);
        return Result.newInstance(YGoodsOrder.class).setData(goodsOrder).setCode(200).setMsg("查询成功");
    }



    /**
     * 传一个对象，根据id去修改里面的信息
     * 在商城订单消费者里面用了，用于去修改商品的冻结量和数量
     * @param yGoodsOrder 商品对象
     * @return
     * @throws YogaException
     */
    @PostMapping("/updateByIdGoodsOrder")
    @ApiOperation(value = "传一个订单对象，根据id去修改里面的信息")
    public Result updateByIdGoodsOrder(@RequestBody YGoodsOrder yGoodsOrder)throws YogaException{
        goodsOrderService.updateByIdGoodsOrder(yGoodsOrder);
        return Result.newInstance(null).setCode(200).setMsg("修改成功");
    }


    /**
     * 分页查询
     * @param form pageNum; pageSize;
     * @return
     * @throws YogaException
     */
    @GetMapping("/loadPageGoodsOrder")
    @ApiOperation(value = "分页查询订单接口")
    public Result loadPageGoodsOrder( PageForm form) throws YogaException {
        Page<YGoodsOrder> page = goodsOrderService.loadPageGoodsOrder(BeanUtil.toBean(form, PageParam.class));
        return Result.newPageInstance(YGoodsOrder.class).setMsg("查询成功").setCode(200).setData(page);
    }

}

